/*
 * Copyright 2020-2021 the original author or authors.
 *
 * Licensed under the General Public License, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.gnu.org/licenses/gpl-3.0.en.html
 */

package team.seekers.hula.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

public class FilterUtils {

    public static String getRealIp(HttpServletRequest request) {
        String realIp = Optional.ofNullable(request.getHeader("x-real-ip"))
                                .orElse(String.valueOf(request.getRemoteAddr()));
        int index = realIp.indexOf(':');
        if (index != -1) {
            realIp = realIp.substring(0, index);
        }
        return realIp;
    }

    public static void returnWithStatus(HttpServletResponse response,
                                        HttpStatus httpStatus,
                                        String msg) throws IOException {
        // 返回鉴权失败的消息
        JSONObject message = new JSONObject();
        message.put("code", httpStatus.value());
        message.put("message", msg);
        message.put("timestamp", String.valueOf(System.currentTimeMillis()));
        message.put("data", null);
        response.setStatus(httpStatus.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSON.toJSONString(message));
    }
}
